import { defineComponent, PropType, ref } from 'vue';
import { QuestionItemType, QuestionType } from '../typing';
import ScaleNode from './scale-node';
import './style.css';

export default defineComponent({
  props: {
    question: {
      type: Object as PropType<QuestionType>,
    },
    language: {
      type: String as PropType<'zh' | 'en'>,
    },
    value: {
      type: Object as PropType<any>,
    },
  },
  emits: ['update:value'],
  setup(props, { emit }) {
    const { question, language, value } = props;
    const mode = ref<string>(question?.mode || '');
    const _value = ref(value);

    const questionProper =
      language === 'zh' ? question?.questionProperZh : question?.questionProperEn;

    const onMouseenter = (questionItem: QuestionItemType) => {
      changeHoverStatus(questionItem.value);
    };

    const onMouseleave = () => {
      changeHoverStatus(_value.value);
    };

    const onClick = (questionItem: QuestionItemType) => {
      _value.value = questionItem.value;
      changeHoverStatus(_value.value);
      emit('update:value', _value.value);
    };

    const changeHoverStatus = (itemValue?: number) => {
      questionProper?.items?.forEach(eachItem => {
        eachItem.isHovered = false;
      });
      if (itemValue === undefined) {
        return;
      }
      if (itemValue === -1) {
        questionProper!.items![questionProper!.items!.length - 1].isHovered = true;
        return;
      } else {
        questionProper?.items?.forEach(eachItem => {
          if (eachItem.value <= itemValue && eachItem.value !== -1) {
            eachItem.isHovered = true;
          }
        });
      }
    };

    return () => {
      return (
        <div
          class={[
            'question-container',
            'question-scale-container',
            { 'question-design': mode.value === 'design' },
          ]}
        >
          <div class="question-title" v-html={questionProper!.title}></div>
          <div class="scale-question-node-container">
            {questionProper?.items?.map(eachItem => {
              return (
                <ScaleNode
                  key={`scale-question-${question?.id}-node-${eachItem.id}`}
                  questionItem={eachItem}
                  onMouseenter={onMouseenter}
                  onMouseleave={onMouseleave}
                  onClick={onClick}
                />
              );
            })}
          </div>
        </div>
      );
    };
  },
});
